import type { Ref } from "vue";

/**
 * 重置表单
 */
export function resetForm(form: any, defaultValueObj: any, formRef?: Ref) {
  for (const key in form.value) {
    if (key in defaultValueObj) {
      form.value[key] = defaultValueObj[key];
    } else {
      delete form.value[key];
    }
  }

  formRef?.value.resetFields();
}

/**
 * 树结构搜索
 */
export function treeSearch(tree: any[], targetKey: string, targetValue: string | number): any | null {
  if (!tree || tree.length === 0) {
    return null;
  }

  for (const item of tree) {
    if (item[targetKey] === targetValue) {
      return item;
    }
    if (item.children && item.children.length > 0) {
      const result = treeSearch(item.children, targetKey, targetValue);
      if (result !== null) {
        return result;
      }
    }
  }

  return null;
}

export function downloadFile(url: string, fileName: string = ""): void {
  // 创建隐藏的可下载链接
  const element = document.createElement("a");
  element.setAttribute("href", url);

  // 如果指定了文件名，则设置下载属性
  if (fileName) {
    element.setAttribute("download", fileName);
  }

  // 触发点击
  document.body.appendChild(element);
  element.click();

  // 然后移除
  document.body.removeChild(element);
}
